// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database();
const maxDistance = 0.5; //km
const SECOND = 1000,
    MINUTE = SECOND * 60,
    HOUR = MINUTE * 60;
// 云函数入口函数
exports.main = async (event, context) => new Promise((resolve, reject) => {
    const wxContext = cloud.getWXContext()
    console.log(event)
    // basicGroupHandle(event,wxContext)
    const userId = wxContext.OPENID || event.userId
    db.collection('code').add({
        data: {
            code: event.code,
            time: new db.serverDate(),
            lat: event.position.lat,
            lng: event.position.lng,
            userId: userId,
            role: null,
            group: null
        }
    }).then((codeRes) => {
        //查找时间范围内相同的CODER
        db.collection('code').where({
            code: event.code,
            time: db.command.gt(new Date(new Date().getTime() - 30 * MINUTE))
        }).orderBy('time', 'asc').get().then(res => {
            if (res.data.length) {
                //遍历CODER
                for (const user of res.data) {
                    if (user.userId === userId) continue;   //排除自己
                    //计算两者距离,当距离小于范围时加入组
                    const distance = GetDistance(user.lat, user.lng, event.position.lat, event.position.lng)
                    console.log('/n两者距离:', distance);
                    if (user.group && distance < maxDistance) {
                        db.collection('code').doc(codeRes._id).update({
                            data: {
                                group: user.group
                            }
                        }).then(() => {
                            //得到当前组内成员信息
                            db.collection('code').where({
                                group: user.group
                            }).orderBy('time', 'asc').get()
                                .then(member => {
                                    const order = member.data.map(usr => ({ _id: usr.userId }));
                                    const orderList = order.map(item => item._id);
                                    console.log('\n', orderList)
                                    db.collection('user').where(
                                        db.command.or(order)
                                    ).get().then(member => {
                                        const result = member.data.sort((a, b) => {
                                            return orderList.indexOf(a._id) - orderList.indexOf(b._id)
                                        })
                                        console.log(result)
                                        db.collection('group').doc(user.group).get().then(group => {
                                            resolve({
                                                group: group.data,
                                                member: result,
                                                create: false,
                                                codeId: codeRes._id
                                            })
                                        })
                                    })
                                })
                        }).catch(err => { console.log(err); reject(err); })
                        return;
                    }
                }
            }
            //创建组
            makeupGroup(userId)
                .then(group => {
                    db.collection('code').doc(codeRes._id).update({
                        data: {
                            group: group._id
                        }
                    }).then(() => {
                        db.collection('user').doc(userId).get().then(usr => {
                            resolve({
                                group,
                                member: [usr.data],
                                create: true,
                                codeId: codeRes._id
                            })
                        })

                    }).catch(err => { console.log(err); reject(err); })

                }).catch(err => { console.log(err); reject(err); })
            return;
        }).catch(err => { console.log(err); reject(err); })
    })
})
function makeupGroup(userId) {
    return new Promise((resolve, reject) => {
        const data = {
            createTime: new Date(),
            creator: userId,
            mainOwner: null,
            subOwner: null,
            init: false,
            project: {}
        }
        db.collection('group').add({
            data
        }).then(res => {
            resolve({
                ...data,
                _id: res._id
            })
        }).catch(err => reject(err))
    })
}

function Rad(d) {
    return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
}
//计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
function GetDistance(lat1, lng1, lat2, lng2) {
    var radLat1 = Rad(lat1);
    var radLat2 = Rad(lat2);
    var a = radLat1 - radLat2;
    var b = Rad(lng1) - Rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137; // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000; //输出为公里
    //s=s.toFixed(4);
    return s;
}